package com.market.controller;

import com.market.entity.Role;
import com.market.service.RoleService;
import com.market.utils.PageResult;
import com.market.utils.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
public class RoleController {
    
    @Autowired
    private RoleService roleService;
    
    /**
     * 获取所有角色列表
     */
    @GetMapping("/list")
    public Map<String, Object> list() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Role> roles = roleService.findAll();
            result.put("flag", true);
            result.put("data", roles);
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取角色列表失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 分页查询角色
     */
    @GetMapping("/search")
    public Map<String, Object> search(
            @RequestParam(required = false) String roleName,
            @RequestParam(required = false) String roleCode,
            @RequestParam(required = false, defaultValue = "1") Integer currentPage,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        try {
            PageResult<Role> pageResult = roleService.findByPage(roleName, roleCode, currentPage, pageSize);
            
            result.put("flag", true);
            result.put("data", pageResult.getList());
            result.put("total", pageResult.getTotalCount());
            result.put("currentPage", pageResult.getCurrentPage());
            result.put("pageSize", pageResult.getPageSize());
            result.put("totalPages", pageResult.getTotalPages());
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "搜索角色失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 根据ID获取角色详情
     */
    @GetMapping("/{id}")
    public Map<String, Object> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Role role = roleService.findById(id);
            if (role != null) {
                result.put("flag", true);
                result.put("data", role);
            } else {
                result.put("flag", false);
                result.put("message", "未找到ID为" + id + "的角色");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "获取角色详情失败: " + e.getMessage());
        }
        return result;
    }
    
    /**
     * 添加角色
     */
    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody Role role, HttpServletRequest request) {
        // 设置创建者为当前登录用户
        Long userId = SessionUtil.getCurrentUserId();
        if (userId != null) {
            role.setCreatedBy(userId);
        }
        return roleService.add(role);
    }
    
    /**
     * 修改角色
     */
    @PostMapping("/update")
    public Map<String, Object> update(@RequestBody Role role, HttpServletRequest request) {
        // 设置修改者为当前登录用户
        Long userId = SessionUtil.getCurrentUserId();
        if (userId != null) {
            role.setModifyBy(userId);
        }
        return roleService.update(role);
    }
    
    /**
     * 删除角色
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        return roleService.deleteById(id);
    }
    
    /**
     * 检查角色是否可删除
     */
    @GetMapping("/checkDelete/{id}")
    public Map<String, Object> checkDelete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean hasUsers = roleService.hasRelatedUsers(id);
            result.put("flag", true);
            result.put("canDelete", !hasUsers);
            if (hasUsers) {
                result.put("message", "该角色下存在用户，不能删除");
            }
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", "检查角色是否可删除失败: " + e.getMessage());
        }
        return result;
    }
}
